#
# dashboard.py
# 
# The Dashboard controls such items as the Access Manager which controls user
# access to CRUD functions for the eCataloger applicaiton.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Copyright 2009,2010- Jeremy Nelson

# Import statements
import cgi,logging,datetime
import datetime,os
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp.util import login_required
from django.utils import simplejson
from common.app_info import *
from catalog_manager import *
import FRBRData,MODSData,ApplicationAndHelpData

class HomePage(webapp.RequestHandler):
    ''' Default view for performing basic management functions for app '''

    @login_required
    def get(self):
        ''' Standard GET request '''
        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        entities = list()
        entities.extend(get_entities(FRBRData))
        entities.extend(get_entities(MODSData))
        alpha_entities = {'a':[],'b':[],'c':[],'d':[],
                       'e':[],'f':[],'g':[],'h':[],
                       'i':[],'j':[],'k':[],'l':[],
                       'm':[],'n':[],'o':[],'p':[],
                       'q':[],'r':[],'s':[],'t':[],
                       'u':[],'v':[],'w':[],'w':[],
                       'y':[],'z':[]}
        for entity in entities:
            first_letter = entity['name'][0].lower()
            alpha_entities[first_letter].append(entity)
##            if alpha_entities.has_key(first_letter):
##                alpha_entities[first_letter].append(entity)
##            else:
##                alpha_entities[first_letter]=[entity,]
        endeavor_types = [{'class':'WebSiteEndeavor',
                           'pretty_name':'Website'},
                          {'class':'PurchasedElectronicResourceEndeavor',
                           'pretty_name':'Remote Database'}]
        user_dict = ApplicationAndHelpData.getUserRights(users.get_current_user())
        user_dict['email'] = users.get_current_user().email()
        app_query = ApplicationAndHelpData.AppInfo.all()
        if app_query.count() > 0:
            app_info = app_query[0]
        else:
            app_info = None
        all_users = {'admin':[],'editors':[],'contributors':[]}
        for row in ApplicationAndHelpData.Administrators.all().order("user"):
            all_users['admin'].append(row)
        for row in ApplicationAndHelpData.Editors.all().order("user"):
            all_users['editors'].append(row)
        all_users['contributors'] = ApplicationAndHelpData.Contributors.all().order("user")
        template_values = {
            'auth_text':url_linktext,
            'auth_url':url,
            'user':user_dict,
            'all_users':all_users,
            'corporate_bodies':FRBRData.CorporateBody.all().order("display_form"),
            'concepts':FRBRData.Concept.all().order("display_form"),
            'endeavor_types':endeavor_types,
            'all_entities':sorted(alpha_entities.items(),key=lambda x:x[0]),
#            'all_entities':sorted(entities,key=lambda x: x['name'].lower()),
            'languages':MODSData.languageTerm.all().order("display_form"),
            'app_info':app_info}
        path = os.path.join(os.path.dirname(__file__),
                            'templates/dashboard.html')
        self.response.out.write(template.render(path,template_values))
        
def main():
    app = webapp.WSGIApplication([
        ('/manage',HomePage),
        ],debug=True)
    util.run_wsgi_app(app)

if __name__ == '__main__':
    main()
